"use strict";
const { app, BrowserWindow, Tray, Menu, ipcMain } = require("electron/main");
const path = require("path");
const iconPath = path.join(__dirname, "../assets/tool.png");
let tray, mainWindow = null;
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";
const createWindow = () => {
  mainWindow = new BrowserWindow({
    width: 1400,
    height: 800,
    icon: iconPath,
    title: "ToolDesk",
    frame: false,
    webPreferences: {
      backgroundThrottling: false,
      //设置应用在后台正常运行
      nodeIntegration: true,
      //设置能在页面使用nodejs的API
      contextIsolation: false
    }
  });
  if (process.env.VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL);
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(join(__dirname, "../../dist/index.html"));
  }
};
const setTrayConfig = () => {
  tray = new Tray(iconPath);
  tray.setToolTip("ToolDesk");
  tray.on("click", () => {
    if (mainWindow.isVisible()) {
      mainWindow.hide();
    } else {
      mainWindow.show();
    }
  });
  tray.on("right-click", () => {
    const menuConfig = Menu.buildFromTemplate([
      {
        label: "Quit",
        click: () => app.quit()
      }
    ]);
    tray.popUpContextMenu(menuConfig);
  });
};
app.whenReady().then(() => {
  createWindow();
  setTrayConfig();
  mainWindow.on("maximize", () => {
    mainWindow.webContents.send("mainWindow:opreate", true);
  });
  mainWindow.on("unmaximize", () => {
    mainWindow.webContents.send("mainWindow:opreate", false);
  });
});
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
    tray = null;
    mainWindow = null;
  }
});
ipcMain.on("mainWindow:opreate", (_, arg) => {
  const map = {
    close: () => {
      app.quit();
    },
    max: () => {
      mainWindow.maximize();
    },
    shrink: () => {
      mainWindow.restore();
    },
    min: () => {
      mainWindow.minimize();
    },
    tray: () => {
      mainWindow.hide();
    }
  };
  map[arg] && map[arg]();
});
